/**
 * @author Jeff
 * 
 * Graphic User Interface for IDrunk
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;
import java.sql.*;
import java.util.Properties;
import model.DatabaseCommunicator;
import java.awt.event.MouseListener; 
import javax.swing.ListSelectionModel;
import javax.swing.table.*;

/**
 *
 * @author Jeff
 */
public class IDrunkUI extends javax.swing.JFrame {
	
	String deleteKey;

	String userName = "REMOTE";
	String password = "DSPWEBREMOTE";
	String dbms = "mysql";
	String serverName = "moe.is-a-geek.com";
	String portNumber = "3306";
	String dbName = "idrunk-steve";
	String activeTable = "null";

    /**
     * Creates new form IDrunkUI
     */
    public IDrunkUI() {
        Connection conn;
        try {
			conn = getConnection();
			initComponents(conn);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }
    
    /**
     * Used to connect to the database
     */
    public Connection getConnection() throws SQLException {

        Connection conn = null;
        Properties connectionProps = new Properties();
        connectionProps.put("user", this.userName);
        connectionProps.put("password", this.password);
        connectionProps.put("DATABASE", this.dbName);

        if (this.dbms.equals("mysql")) {
        	try {
	            conn = DriverManager.getConnection(
	                       "jdbc:" + this.dbms + "://" +
	                       this.serverName +
	                       ":" + this.portNumber + "/" + this.dbName,
	                       connectionProps);
        	} catch (SQLException ex) {
        	    // handle any errors
        	    System.out.println("SQLException: " + ex.getMessage());
        	    System.out.println("SQLState: " + ex.getSQLState());
        	    System.out.println("VendorError: " + ex.getErrorCode());
        	}
        }
        
        return conn;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents(Connection conn) {
    	DatabaseCommunicator.dbc = new DatabaseCommunicator(conn);
    	    	
        //searchBar = new javax.swing.JFormattedTextField();
        
        beersButton = new javax.swing.JButton();
        beersButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	activeJTable = beerJTable;
            	activeTable = "beer";
            	refresh();
            	tableScrollPane.setViewportView(activeJTable);
            }
        });
        
        breweriesButton = new javax.swing.JButton();
        breweriesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	activeJTable = breweryJTable;
            	activeTable = "brewery";
            	refresh();
            	tableScrollPane.setViewportView(activeJTable);
            }
        });
        
        winesButton = new javax.swing.JButton();
        winesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	activeJTable = wineJTable;
            	activeTable = "wine";
            	refresh();
            	tableScrollPane.setViewportView(activeJTable);
            }
        });
        
        wineriesButton = new javax.swing.JButton();
        wineriesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	activeJTable = wineryJTable;
            	activeTable = "winery";
            	refresh();
            	tableScrollPane.setViewportView(activeJTable);
            }
        });
        
        spiritsButton = new javax.swing.JButton();
        spiritsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	activeJTable = spiritJTable;
            	activeTable = "spirit";
            	refresh();
            	tableScrollPane.setViewportView(activeJTable);
            }
        });
        
        distilleriesButton = new javax.swing.JButton();
        distilleriesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	activeJTable = distilleryJTable;
            	activeTable = "distillery";
            	refresh();
            	tableScrollPane.setViewportView(activeJTable);
            }
        });
        
        tableScrollPane = new javax.swing.JScrollPane();
        activeJTable = new javax.swing.JTable(){
        	public boolean isCellEditable(int rowIndex, int colIndex) {
        		return false;   //Disallow the editing of any cell
        	}
        };
        beerJTable = new javax.swing.JTable(){
        	public boolean isCellEditable(int rowIndex, int colIndex) {
        		return false;   //Disallow the editing of any cell
        	}
        };
        wineJTable = new javax.swing.JTable(){
        	public boolean isCellEditable(int rowIndex, int colIndex) {
        		return false;   //Disallow the editing of any cell
        	}
        };
        spiritJTable = new javax.swing.JTable(){
        	public boolean isCellEditable(int rowIndex, int colIndex) {
        		return false;   //Disallow the editing of any cell
        	}
        };
        breweryJTable = new javax.swing.JTable(){
        	public boolean isCellEditable(int rowIndex, int colIndex) {
        		return false;   //Disallow the editing of any cell
        	}
        };
        wineryJTable = new javax.swing.JTable(){
        	public boolean isCellEditable(int rowIndex, int colIndex) {
        		return false;   //Disallow the editing of any cell
        	}
        };
        distilleryJTable = new javax.swing.JTable(){
        	public boolean isCellEditable(int rowIndex, int colIndex) {
        		return false;   //Disallow the editing of any cell
        	}
        };
        
        newEntryButton = new javax.swing.JButton();
        newEntryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	if(!activeTable.equals("null")){
	            	NewEntryFrame nef = new NewEntryFrame();
	            	nef.validate();
	            	nef.setVisible(true);
	            	nef.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            	}
            }
        });
        
        deleteEntryButton = new javax.swing.JButton();
        deleteEntryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	if(!activeTable.equals("null")){
	            	int column = 0;
	            	int row = activeJTable.getSelectedRow();
	            	
	            	Object deleteEntry = new Object();
	            	if(column != -1 && row != -1){
	            		deleteEntry = activeJTable.getValueAt(row, column);
	            	}
	            	deleteKey = deleteEntry.toString();
	            	// Creates the SQL statement needed to delete an entry from the table
	            	System.out.println("Delete key " + deleteKey);
	            	String sqlStmt = "DELETE FROM " + activeTable + " WHERE name = " + "'" + deleteKey + "'";
	            	DatabaseCommunicator.dbc.delete(sqlStmt);
	            	refresh();
            	}
            }
        });
        
        //additionalLabel = new javax.swing.JLabel();
        
        modifyButton = new javax.swing.JButton();
        modifyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {

        		String name = "N/A";
        		
	        	if(!activeTable.equals("null")){
	        		name = activeJTable.getValueAt(activeJTable.getSelectedRow(),0).toString();
	        		if (activeTable == "beer" || activeTable == "wine" || activeTable == "spirit") {
	        			Double price = Double.parseDouble(activeJTable.getValueAt(activeJTable.getSelectedRow(),1).toString());
	        			String type = activeJTable.getValueAt(activeJTable.getSelectedRow(),2).toString();
	        			int numDrank = Integer.parseInt(activeJTable.getValueAt(activeJTable.getSelectedRow(),3).toString());
	        			int proof = Integer.parseInt(activeJTable.getValueAt(activeJTable.getSelectedRow(),4).toString());
		            	if(activeTable.equals("beer")){
		            		String flavorings = activeJTable.getValueAt(activeJTable.getSelectedRow(),5).toString();
		            		ModifyEntryFrame mef = new ModifyEntryFrame(name, price, proof, numDrank, flavorings, type);
		            		mef.setVisible(true);
		            		mef.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		            	}
		            	else if(activeTable.equals("wine")){
		            		int year = Integer.parseInt(activeJTable.getValueAt(activeJTable.getSelectedRow(),5).toString());
		            		int fruitWine = Integer.parseInt(activeJTable.getValueAt(activeJTable.getSelectedRow(),6).toString());
		            		String pairings = activeJTable.getValueAt(activeJTable.getSelectedRow(),7).toString();
		            		ModifyEntryFrame mef = new ModifyEntryFrame(name, price, proof, numDrank, pairings, fruitWine, year, type);
		            		mef.setVisible(true);
		            		mef.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		            	}
		            	else if(activeTable.equals("spirit")){
		            		String distilledFrom = activeJTable.getValueAt(activeJTable.getSelectedRow(),5).toString();
		            		ModifyEntryFrame mef = new ModifyEntryFrame(name, price, distilledFrom, proof, numDrank, type);
		            		mef.setVisible(true);
		            		mef.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		            	}
	        		} else {
	            		int yearEstablished = Integer.parseInt(activeJTable.getValueAt(activeJTable.getSelectedRow(),1).toString());
	            		String website = activeJTable.getValueAt(activeJTable.getSelectedRow(),2).toString();
		            	if(activeTable.equals("brewery")){
		            		int micro = Integer.parseInt(activeJTable.getValueAt(activeJTable.getSelectedRow(),3).toString());
		            		ModifyEntryFrame mef = new ModifyEntryFrame(name, yearEstablished, website, micro);
		            		mef.setVisible(true);
		            		mef.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		            	}
		            	else if(activeTable.equals("winery")){
		            		int currProd = Integer.parseInt(activeJTable.getValueAt(activeJTable.getSelectedRow(),3).toString());
		            		int acres = Integer.parseInt(activeJTable.getValueAt(activeJTable.getSelectedRow(),3).toString());
		            		String wineMaker = activeJTable.getValueAt(activeJTable.getSelectedRow(),5).toString();
		            		ModifyEntryFrame mef = new ModifyEntryFrame(name, yearEstablished, website, currProd, wineMaker, acres);
		            		mef.setVisible(true);
		            		mef.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		            	}
		            	else if(activeTable.equals("distillery")){
		            		String founder = activeJTable.getValueAt(activeJTable.getSelectedRow(),3).toString();
		            		ModifyEntryFrame mef = new ModifyEntryFrame(name, yearEstablished, website, founder);
		            		mef.setVisible(true);
		            		mef.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		            	}
	        		}
	        	}
            	
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

       // searchBar.setText("Search...");

        beersButton.setText("Beers");

        breweriesButton.setText("Breweries");

        winesButton.setText("Wines");

        wineriesButton.setText("Wineries");

        spiritsButton.setText("Spirits");

        distilleriesButton.setText("Distilleries");
        
        refreshAll();
        
        tableScrollPane.setViewportView(activeJTable);

        newEntryButton.setText("New Entry");

        deleteEntryButton.setText("Delete Entry");

        modifyButton.setText("Modify Entry");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(beersButton)
                    .addComponent(breweriesButton)
                    .addComponent(winesButton)
                    .addComponent(wineriesButton)
                    .addComponent(spiritsButton)
                    .addComponent(distilleriesButton))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        //.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 501, Short.MAX_VALUE)
                        .addComponent(tableScrollPane)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(1, 1, 1)
                            .addComponent(newEntryButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(modifyButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(deleteEntryButton)
                            .addGap(18, 18, 18)
                            //.addComponent(searchBar)))
                    //.addComponent(additionalLabel))
                .addGap(10, 10, Short.MAX_VALUE)))
        )));
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(deleteEntryButton)
                        .addComponent(modifyButton)
                        .addComponent(newEntryButton)))
                    //.addComponent(searchBar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(beersButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(breweriesButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(winesButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(wineriesButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spiritsButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(distilleriesButton))
                    .addComponent(tableScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                //.addComponent(additionalLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                //.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>
    
    public void refresh(){
    	DefaultTableModel model = DatabaseCommunicator.dbc.populateTable(activeTable);
    	activeJTable.setModel(model);
    }

    // Refreshes all the tables
    public void refreshAll(){
    	DefaultTableModel model = DatabaseCommunicator.dbc.populateTable("beer");
        beerJTable.setModel(model);
        model = DatabaseCommunicator.dbc.populateTable("wine");
        wineJTable.setModel(model);
        model = DatabaseCommunicator.dbc.populateTable("spirit");
        spiritJTable.setModel(model);
        model = DatabaseCommunicator.dbc.populateTable("brewery");
        breweryJTable.setModel(model);
        model = DatabaseCommunicator.dbc.populateTable("winery");
        wineryJTable.setModel(model);
        model = DatabaseCommunicator.dbc.populateTable("distillery");
        distilleryJTable.setModel(model);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IDrunkUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IDrunkUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IDrunkUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IDrunkUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new IDrunkUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    //private javax.swing.JLabel additionalLabel;
    private javax.swing.JTable activeJTable;
    private javax.swing.JButton beersButton;
    private javax.swing.JButton breweriesButton;
    private javax.swing.JButton deleteEntryButton;
    private javax.swing.JButton distilleriesButton;
    //private javax.swing.JTextArea infoArea;
    //private javax.swing.JScrollPane infoScrollPane;
    private javax.swing.JButton modifyButton;
    private javax.swing.JButton newEntryButton;
    //private javax.swing.JFormattedTextField searchBar;
    private javax.swing.JButton spiritsButton;
    private javax.swing.JScrollPane tableScrollPane;
    private javax.swing.JButton wineriesButton;
    private javax.swing.JButton winesButton;
    
    private javax.swing.JTable beerJTable;
    private javax.swing.JTable wineJTable;
    private javax.swing.JTable spiritJTable;
    private javax.swing.JTable breweryJTable;
    private javax.swing.JTable wineryJTable;
    private javax.swing.JTable distilleryJTable;
    // End of variables declaration
}
